import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {
    /**
     * 根据用户名查询用户
     */
    public static User getUserByUsername(String username) {
        String sql = "SELECT * FROM users WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return createUserFromResultSet(rs);
            }
        } catch (SQLException e) {
            System.err.println("查询用户失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 根据ID查询用户
     */
    public static User getUserById(String id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return createUserFromResultSet(rs);
            }
        } catch (SQLException e) {
            System.err.println("查询用户失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 获取所有用户
     */
    public static List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                users.add(createUserFromResultSet(rs));
            }
        } catch (SQLException e) {
            System.err.println("查询所有用户失败: " + e.getMessage());
        }
        return users;
    }

    /**
     * 从结果集中创建用户对象
     */
    private static User createUserFromResultSet(ResultSet rs) throws SQLException {
        String id = rs.getString("id");
        String username = rs.getString("username");
        String password = rs.getString("password");
        String phone = rs.getString("phone");
        String userType = rs.getString("user_type");

        User user;
        switch (userType) {
            case "管理员":
                user = new Admin(id, username, password, phone);
                break;
            case "经理":
                user = new Manager(id, username, password, phone);
                break;
            case "前台":
                user = new FrontDesk(id, username, password, phone);
                break;
            default:
                throw new SQLException("未知用户类型: " + userType);
        }

        user.setRegisterTime(rs.getTimestamp("register_time"));
        user.loginAttempts = rs.getInt("login_attempts");
        user.locked = rs.getBoolean("locked");

        return user;
    }
}
